const cloud = require('wx-server-sdk')

cloud.init()
const db = cloud.database();
const ONE_DAY = 24 * 60 * 60 * 1000;

// 云函数入口函数
exports.main = async (event, context) => new Promise((resolve, reject) => {
    // const wxContext = cloud.getWXContext()
    console.log(event)
    const {
        group,
        needDetail,
        memberIds
    } = event
    if (memberIds && memberIds.length && !needDetail) {
        const time = new Date().getTime()
        refreshMember(group, memberIds, time).then(resolve)
    } else {
        db.collection('code').where({
            // code: code,
            group: group
        }).orderBy('time', 'asc').get().then(member => {
            const order = member.data.map(item => item.userId)
            // console.log(order)
            db.collection('user').where(
                db.command.or(member.data.map(usr => ({
                    _id: usr.userId
                })))
            ).get().then(res => {
                const member = res.data.sort((a, b) => order.indexOf(a._id) - order.indexOf(b._id))
                if (!needDetail) {
                    resolve({
                        member
                    })
                } else {
                    //继续获取详细信息
                    db.collection('group').doc(group).get().then(groupInfo => {
                        for (const user of member) {
                            if (user._id === groupInfo.data.mainOwner) {
                                groupInfo.data.mainOwner = user;
                            }
                            if (user._id === groupInfo.data.subOwner) {
                                groupInfo.data.subOwner = user;
                            }
                        }
                        db.collection('mission').where({
                            projectId: group
                        }).get().then(missionInfo => {
                            let computeList = [];
                            missionInfo.data.forEach(item => {
                                //判断任务是否需要计算开始时间
                                if (item && item.front && item.front.length) {
                                    computeList.push(
                                        figureOutStartDate(item).then(res => {
                                            if (res)
                                                figureOutEndDate(item)
                                        })
                                    )
                                }
                            })
                            Promise.all(computeList).then(() => {
                                resolve({
                                    member,
                                    group: groupInfo.data,
                                    mission: missionInfo.data
                                })
                            })

                        })
                    })

                }
            }).catch(err => {
                console.error(err)
            })
        }).catch(err => {
            console.error(err)
        })
    }
})

function getMissionItem(id) {
    return db.collection('mission').doc(id).get().then(res => {
        return res.data
    })
}
async function figureOutEndDate(item) {
    if (item.end) return item.end;
    else {
        let end = null;
        if (item.front && item.front.length) {
            let startPoint = Date.parse(await figureOutStartDate(item));
            if (startPoint) {
                for (let j = 0; j < item.last; startPoint += ONE_DAY) {
                    const tempDate = new Date(startPoint);
                    const day = tempDate.getDay();
                    //排除周六周日
                    if (day !== 0 && day !== 6) {
                        j++;
                    }
                }
                startPoint -= ONE_DAY;
                item.end = end = new Date(startPoint).toLocaleDateString();
                // console.log('206', end)
            }
        }
        // console.log('任务起始时间', start);
        return end;
    }
}
async function figureOutStartDate(item) {
    if (item.start) return item.start;
    else {
        let start = null;
        if (item.front && item.front.length) {
            for (const id of item.front) {
                const targetMission = await getMissionItem(id);
                const targetDateObject = await figureOutEndDate(targetMission);

                let targetDate;
                if (targetDateObject) {
                    targetDate = Date.parse(targetDateObject) + ONE_DAY;
                    if (!start || start < targetDate) {
                        start = targetDate;
                    }
                }

            }
            // console.log('230', start)
            if (start) item.start = start = new Date(start).toLocaleDateString();
        }
        // console.log('任务起始时间', start);
        return start;
    }
}

function refreshMember(projectId, ids, time) {
    return new Promise((resolve)=>{
        db.collection('code').where({
            group: projectId
        }).orderBy('time', 'asc').get().then(member=>{
            const order = member.data.map(item => item.userId)
            const memberSetLatest = new Set(order);
            const memberSetOrigin = new Set(ids);
            const intersectionSet = new Set([...memberSetLatest, ...memberSetOrigin]);
            const currentTime = new Date().getTime();
            if (intersectionSet.size == memberSetLatest.size&&intersectionSet.size==memberSetOrigin.size) {
                if (currentTime - time >= 1000 * 15) {
                    console.log('overtime');
                    resolve();
                } else {
                    console.log('1s later refresh, now ' + (currentTime - time) / 1000 + 's');
                    new Promise((resolve) => {
                        setTimeout(() => {
                            refreshMember(projectId, ids, time).then(resolve)
                        }, 1000, projectId, ids, time)
                    }).then(resolve)
                }
            } else {
                //抓取用户信息
                console.log('get user info data');
                if (member.data.length) {
                    db.collection('user').where(
                        db.command.or(member.data.map(usr => ({
                            _id: usr.userId
                        })))
                    ).get().then(res=>{
                        console.log(res)
                        resolve(res.data.sort((a, b) => order.indexOf(a._id) - order.indexOf(b._id)));
                    })
                } else {
                    resolve();
                }
            }
        })
        
    })
}